<?php
class QueryHelper {
    public static function insertInto($tbl, $fieldValues) {
        $fields = implode(",", array_keys($fieldValues));
        $values = array();
        foreach ($fieldValues as $key=>$value) { $values[] = "'" . $value . "'"; }
        $values = implode(",", $values);
        return "INSERT INTO $tbl ($fields) VALUES ($values)";
    }
    
    public static function update($tbl, $fieldValues, $condition) {
        $fields = "";
        $fieldArr = array();
        foreach ($fieldValues as $field=>$value) {
            if ($field == "update") { $field = "`update`"; }
            if ($field == "group") { $field = "`group`"; }
            if ($value === null) {
                $fieldArr[] = "$field=null";
            } else if ($value == "now()") {
                $fieldArr[] = "$field=now()";
            } else {
                $fieldArr[] = "$field='$value'";
            }
        }
        $fields = implode(",", $fieldArr);
        return "UPDATE $tbl SET $fields WHERE $condition";
    }
    
    public static function select($tbl, $fields, $condition = "true", $joins = "", $distinct = false) {
        $fieldArr = array();
        for ($i = 0; $i < count($fields); $i++) {
            if ($fields[$i]['name'] == "update") { $fields[$i]['name'] = "`update`"; }
            if ($fields[$i]['name'] == "group") { $fields[$i]['name'] = "`group`"; }
            $fieldArr[] = $fields[$i]['name'];
        }
        return "SELECT " . ($distinct ? " DISTINCT " : "") . implode(",", $fieldArr) . " FROM $tbl $joins WHERE $condition";
    }

    public static function bulkInsertInto($tablename, $data) {
        $valueList = "";
        $valueArr = array();
        for ($i = 0; $i <count($data); $i++) {
            $valueArr[] = "'".implode("','", array_values($data[$i])) . "'";
        }
        $fieldList = implode(",", array_keys($data[0]));
        $valueList = "(" . implode("),(", $valueArr) . ")";
        $query = "INSERT INTO $tablename ($fieldList) VALUES $valueList";
        return $query;
    }

    public static function getCount($tbl, $condition) {
        return "SELECT count(*) AS c FROM $tbl WHERE $condition";
    }

    public static function delete($tbl, $condition = "true") {
        return "DELETE FROM $tbl WHERE $condition";
    }
}

?>
